//
//  SQOrderListViewController.m
//  pai
//
//  Created by linjunjing on 14-7-7.
//  Copyright (c) 2014年 linjunjing. All rights reserved.
//

#import "SQOrderListViewController.h"
#import "SQOrderLowViewController.h"
#import "Global.h"
#import "MJRefresh.h"
#import "SQLowOrderTableViewCell.h"
#import "SQChangeOrderTableViewCell.h"
#import "SQOrderRechangeViewController.h"

@interface SQOrderListViewController ()

@end

@implementation SQOrderListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setTitle:@"我的订单"];
    
    //[self getOrderList];
    [self initList];
}

-(void)initList
{
    [self initbutton];
    //初始化滚动列表
    _scrollView = [[UIScrollView alloc]init];
    [_scrollView setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]];
    _scrollView.frame = CGRectMake(0, self.lowButton.frame.origin.y+self.lowButton.frame.size.height, 320, [[UIScreen  mainScreen] bounds].size.height - 44 - self.lowButton.frame.origin.y-self.lowButton.frame.size.height);
    [_scrollView setContentSize:CGSizeMake(320*2, 0)];
    [_scrollView setPagingEnabled:YES];
    [_scrollView setBounces:NO];
    _scrollView.delegate = self;
    [self.view addSubview:_scrollView];
    
    //初始化最低价列表
    self.lowTableView = [[UITableView alloc] init];;
    self.lowTableView.frame =CGRectMake(0, 0, 320, _scrollView.frame.size.height);
    self.lowTableView.tag = 2000;
    self.lowTableView.delegate = self;
    self.lowTableView.dataSource = self;
    [self.lowTableView setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]];
    self.lowTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_scrollView addSubview:self.lowTableView];
    
    //初始化兑换列表
    self.changeTableView = [[UITableView alloc] init];;
    self.changeTableView.frame =CGRectMake(320, 0, 320, _scrollView.frame.size.height);
    self.changeTableView.tag = 2001;
    self.changeTableView.delegate = self;
    self.changeTableView.dataSource = self;
    [self.changeTableView setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]];
    self.changeTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_scrollView addSubview:self.changeTableView];
    
    // 2.集成刷新控件
    [self addHeader];
    //[self addFooter];
}

- (void)addHeader
{
    NSLog(@"add header");
    __unsafe_unretained typeof(self) vc = self;
    // 添加下拉刷新头部控件
    [self.lowTableView addHeaderWithCallback:^{
        NSLog(@"low add");
        // 进入刷新状态就会回调这个Block
        [vc doActionupdata];
    } dateKey:@"collection"];
    [self.changeTableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        [vc doActionupdata];
    } dateKey:@"collection"];
    // dateKey用于存储刷新时间，也可以不传值，可以保证不同界面拥有不同的刷新时间
    
#warning 自动刷新(一进入程序就下拉刷新)
    [self.lowTableView headerBeginRefreshing];
}
- (void)addFooter
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加上拉刷新尾部控件
    [self.lowTableView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        [vc doActionLoadMore];
    }];
    [self.changeTableView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        [vc doActionLoadMore];
    }];
}
-(void)doActionupdata
{
    NSLog(@"do action update ");
    int currentIndex = _scrollView.contentOffset.x/320;
    NSLog(@"currentIndex:%d",currentIndex);
    if (currentIndex == 0) {
        [self getOLowList];
    }else if (currentIndex == 1)
    {
        [self getChangeList];
    }
}
-(void)doActionLoadMore
{
    int currentIndex = _scrollView.contentOffset.x/320;
    if (currentIndex == 0) {
        
    }else if (currentIndex == 1)
    {
        
    }
}
-(void)getOLowList
{
    NSLog(@"get low list");
    //[self showList];
    my_stuff_t stuff;
    stuff.base.msgtype = 1030;
    stuff.base.len = sizeof(stuff);
    stuff.base.error = 0;
    stuff.type = 4001;
    strcpy(stuff.serialnum, "");
    strcpy(stuff.username, [[Global instance].userinfo.username UTF8String]);
    
    NSMutableData* msgData = [NSMutableData data];
    [msgData appendBytes:&stuff length:sizeof(stuff)];
    
    [super sendData:msgData tag:1 withHUD:NO];
}
-(void)getChangeList
{
    NSLog(@"get low list");
    //[self showList];
    my_stuff_t stuff;
    stuff.base.msgtype = 1030;
    stuff.base.len = sizeof(stuff);
    stuff.base.error = 0;
    stuff.type = 1001;
    strcpy(stuff.serialnum, "");
    strcpy(stuff.username, [[Global instance].userinfo.username UTF8String]);
    
    NSMutableData* msgData = [NSMutableData data];
    [msgData appendBytes:&stuff length:sizeof(stuff)];
    
    [super sendData:msgData tag:2 withHUD:NO];
}
-(void)initbutton
{
    //按钮数
    NSInteger num = 2;
    self.lowButton = [[UIButton alloc]initWithFrame:CGRectMake(0, self.MyNavigationBar.frame.origin.y+self.MyNavigationBar.frame.size.height, 320/num, 40)];
    self.lowButton.tag = 1000;
    [self.lowButton setTitle:@"出价记录" forState:UIControlStateNormal];
    [self.lowButton setBackgroundColor:[UIColor whiteColor]];
    [self.lowButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [self.lowButton addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.lowButton];
    
    self.changeButton = [[UIButton alloc]initWithFrame:CGRectMake(320/num*1, self.MyNavigationBar.frame.origin.y+self.MyNavigationBar.frame.size.height, 320/num, 40)];
    self.changeButton.tag = 1001;
    [self.changeButton setTitle:@"订单" forState:UIControlStateNormal];
    [self.changeButton setBackgroundColor:[UIColor whiteColor]];
    [self.changeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.changeButton addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.changeButton];
    
}
-(void)btnClicked:(UIButton*)btn
{
    if (btn.tag == 1000) {
        [self.lowButton setBackgroundColor:[UIColor whiteColor]];
        [self.changeButton setBackgroundColor:[UIColor whiteColor]];
        
        [self.lowButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [self.changeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        [_scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
        
    }else if (btn.tag == 1001)
    {
        [self.lowButton setBackgroundColor:[UIColor whiteColor]];
        [self.changeButton setBackgroundColor:[UIColor whiteColor]];
        
        [self.lowButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.changeButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        
        [_scrollView setContentOffset:CGPointMake(320, 0) animated:NO];
        if (self.changeDataMarr.count == 0) {
            [self.changeTableView headerBeginRefreshing];
        }
    }
}
-(void)scrollViewDidScroll:(UIScrollView *)theScrollView

{
    CGFloat pageWidth = 320;
    int page = floor((theScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    NSLog(@"theScrollView.contentOffset.x:%f",theScrollView.contentOffset.x);
    NSLog(@"page:%d",page);
    
    if(page == 1) {
        
        //用户拖动了，但是滚动事件没有生效
        
        return;
        
    } else if (page == 0) {
        
    } else {
        
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    int currentIndex = round(scrollView.contentOffset.x/320);
    NSLog(@"scrollView.contentOffset.x:%f",scrollView.contentOffset.x);
    NSLog(@"scrollView.contentOffset.x:%f",scrollView.frame.origin.x);
    NSLog(@"scrollView.contentOffset.x:%f",scrollView.contentSize.width);
    NSLog(@"scrollViewDidEndDecelerating currect:%d",currentIndex);
    if(currentIndex == 0)
    {
        [self.lowButton setBackgroundColor:[UIColor whiteColor]];
        [self.changeButton setBackgroundColor:[UIColor whiteColor]];
        
        [self.lowButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [self.changeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
    }else if (currentIndex == 1){
        [self.lowButton setBackgroundColor:[UIColor whiteColor]];
        [self.changeButton setBackgroundColor:[UIColor whiteColor]];
        
        [self.lowButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.changeButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [_scrollView setContentOffset:CGPointMake(320, 0) animated:NO];
        if (self.changeDataMarr.count == 0) {
            [self.changeTableView headerBeginRefreshing];
        }
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma  mark UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
//    if (tableView.tag == 2000) {
//        return self.lowDataMarr.count;
//    }else if (tableView.tag == 2001){
//        return self.changeDataMarr.count;
//    }else{
//        return 0;
//    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 2000) {
        NSLog(@"self.lowDataMarr.count%lu",(unsigned long)self.lowDataMarr.count);
        return self.lowDataMarr.count;
    }else if (tableView.tag == 2001){
        NSLog(@"self.changeDataMarr.count%lu",(unsigned long)self.changeDataMarr.count);
        return self.changeDataMarr.count;
    }else{
        return 0;
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 2000) {
        return 78;
    }else if (tableView.tag == 2001){
        return 78;
    }else{
        return 68;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 2000) {
        static NSString *orderCellName  = @"SQLowOrderTableViewCell";
        SQLowOrderTableViewCell *ordercell = (SQLowOrderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:orderCellName];
        if (ordercell==nil) {
            ordercell = [[[NSBundle mainBundle] loadNibNamed:@"SQLowOrderTableViewCell" owner:self options:nil] lastObject];
        }
        lowCellObject* obj =[self.lowDataMarr objectAtIndex:indexPath.row];
        NSLog(@"cellForRowAtIndexPath:%@",obj);
        [ordercell setItem:obj];
        ordercell.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
        return ordercell;
    }else if (tableView.tag == 2001){
        static NSString *orderCellName  = @"SQChangeOrderTableViewCell";
        SQChangeOrderTableViewCell *ordercell = (SQChangeOrderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:orderCellName];
        if (ordercell==nil) {
            ordercell = [[[NSBundle mainBundle] loadNibNamed:@"SQChangeOrderTableViewCell" owner:self options:nil] lastObject];
        }
        order_t item;
        [[self.changeDataMarr objectAtIndex:indexPath.row]getValue:&item];
        [ordercell setItem:item];
        ordercell.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
        return ordercell;
    }else{
        
        return  nil;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //点击
    if (tableView.tag == 2000) {
        lowCellObject* obj =[self.lowDataMarr objectAtIndex:indexPath.row];
        SQLowOrderTableViewCell *cell = (SQLowOrderTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        
        SQOrderLowViewController* olvc = [[SQOrderLowViewController alloc]init];
        [olvc setItemWithObject:obj image:cell.imageUrl];
        [self.navigationController pushViewController:olvc animated:YES];
    }else if (tableView.tag == 2001)
    {
        SQChangeOrderTableViewCell *cell = (SQChangeOrderTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        
        order_t item;
        [[self.changeDataMarr objectAtIndex:indexPath.row]getValue:&item];
        SQOrderRechangeViewController* orvc = [[SQOrderRechangeViewController alloc]init];
        [orvc setItemWithObject:item image:cell.imageUrl];
        [self.navigationController pushViewController:orvc animated:YES];
    }
}
//读取数据
-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
//    NSLog(@"get %ld",tag);
    if (tag == 1) {
        if (self.socketLength == 0) {
            ack_my_stuff_t baseInfo;
            [data getBytes:&baseInfo length:sizeof(baseInfo)];
//            NSLog(@"%d",baseInfo.base.msgtype);
//            NSLog(@"%d",baseInfo.base.len);
//            NSLog(@"%d",baseInfo.base.error);
//            NSLog(@"%d",baseInfo.count);
//            NSLog(@"%lu",(unsigned long)data.length);
            if (baseInfo.base.error != ACS_SUCCESS) {
                [self.lowTableView headerEndRefreshing];
                return;
            }
            self.templength =  data.length;
            self.socketLength = baseInfo.base.len;
        }
        else{
            self.templength += data.length;
        }
        if (self.socketTempData == nil) {
            self.socketTempData = [NSMutableData dataWithData:data];
        }else{
            [self.socketTempData appendData:data];
        }
        if (self.templength < self.socketLength) {
            [asyncSocket readDataWithTimeout:-1 tag:tag];
            return;
        }else{
            ack_my_stuff_t baseInfo;
            [self.socketTempData getBytes:&baseInfo length:sizeof(baseInfo)];
            auction_t auction;
            self.lowDataMarr = nil;
            self.lowDataMarr = [NSMutableArray array];
            for (int i =0; i< baseInfo.count; i++) {
                [self.socketTempData getBytes:&auction range:NSMakeRange(self.socketTempData.length - (baseInfo.count - i)*sizeof(auction_t)-8,sizeof(auction_t))];
                for (int j = 0; j<auction.auction_cnt; j++) {
                    lowCellObject* object = [[lowCellObject alloc]init];
                    object.status = auction.status;
                    object.sttime = auction.sttime;
                    object.edtime = auction.edtime;
                    object.strikeprice = auction.strikeprice;
                    object.auction_cnt = auction.auction_cnt;
                    object.userid = [NSString stringWithUTF8String: auction.userid];
                    object.skucode = [NSString stringWithUTF8String: auction.skucode];
                    object.skuname = [NSString stringWithUTF8String: auction.skuname];
                    object.serialnum = [NSString stringWithUTF8String: auction.serialnum];
                    object.auctprice = auction.sublist[j].auctprice;
                    object.created_at = auction.sublist[j].created_at;
                    object.checkflag = auction.sublist[j].checkflag;
                    object.hits = auction.sublist[j].hits;
                    NSLog(@"object:%@",object);
                    [self.lowDataMarr addObject:object];
                }
            }
            self.socketTempData = nil;
            self.socketLength = 0;
            self.templength = 0;
            //加载
            [self.lowTableView headerEndRefreshing];
            //更新列表
            [self.lowTableView reloadData];
        }
    }else if (tag == 2)
    {
        if (self.changeLength == 0) {
            ack_my_stuff_t baseInfo;
            [data getBytes:&baseInfo length:sizeof(baseInfo)];
//            NSLog(@"%d",baseInfo.base.msgtype);
//            NSLog(@"%d",baseInfo.base.len);
//            NSLog(@"%d",data.length);
//            NSLog(@"%d",baseInfo.base.error);
//            NSLog(@"%d",baseInfo.count);
            if (baseInfo.base.error != ACS_SUCCESS) {
                [self.changeTableView headerEndRefreshing];
                return;
            }
            self.tempchangelength =  data.length;
            self.changeLength = baseInfo.base.len;
        }
        else{
            self.tempchangelength += data.length;
        }
        if (self.changeTempData == nil) {
            self.changeTempData = [NSMutableData dataWithData:data];
        }else{
            [self.changeTempData appendData:data];
        }
        if (self.tempchangelength < self.changeLength) {
            [asyncSocket readDataWithTimeout:-1 tag:tag];
            return;
        }else{
            ack_my_stuff_t baseInfo;
            [self.changeTempData getBytes:&baseInfo length:sizeof(baseInfo)];
            order_t auction;
            self.changeDataMarr = nil;
            self.changeDataMarr = [NSMutableArray array];
            for (int i =0; i< baseInfo.count; i++) {
                [self.changeTempData getBytes:&auction range:NSMakeRange(self.changeTempData.length - (baseInfo.count - i)*sizeof(order_t)-8,sizeof(order_t))];
                [self.changeDataMarr addObject:[NSValue value:&auction withObjCType:@encode(struct order_t)]];
//                NSLog(@"***************");
//                NSLog(@"points:%d",auction.status);
//                NSLog(@"points:%d",auction.points);
//                NSLog(@"price:%d",auction.price);
//                NSLog(@"created_at:%d",auction.created_at);
//                NSLog(@"remark:%s",auction.remark);
//                NSLog(@"serialnum:%s",auction.serialnum);
//                NSLog(@"skucode:%s",auction.skucode);
//                NSLog(@"skuname:%s",auction.skuname);
            }
            self.changeTempData = nil;
            self.changeLength = 0;
            self.tempchangelength = 0;
            //加载
            [self.changeTableView headerEndRefreshing];
            //更新列表
            [self.changeTableView reloadData];
        }
    }
}
@end
